package com.gitee.wsl.data.observer


import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.serialization.DeserializationStrategy
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.cbor.Cbor

interface DataChangedObservable {
    val nodeId: String
        get() = KmpKvStoreKeyGenerator.createUniqueKey()
}

inline fun <reified V> DataChangedObservable.observe(key: String): Flow<DataChangeEvent<String, V?>> = KmpKvStoreObserverRegistry.observe<V,V>(nodeId,key){it}

@OptIn(ExperimentalSerializationApi::class)
fun <T> DataChangedObservable.observeDecodeUseByteArray(key: String, deserializer: DeserializationStrategy<T>): Flow<DataChangeEvent<String, T?>> =
    observe<ByteArray?>(key).map {
       it.map { bytes ->
                if (bytes == null)
                    null
                else
                   Cbor.decodeFromByteArray(deserializer, bytes)
            }
    }